from flask import Blueprint, request, current_app
from flask_restful import Resource, Api
from model.like import Like
from model.photo import Photo
from model.user import UserManager
from libs.response import generate_response
from model import db

like_bp = Blueprint("likeapi", __name__, url_prefix="/v1")
api = Api(like_bp)

class LikeView(Resource):
    #
    def post(self):
        # 接收参数(photo_id, action)
        photo_id = request.json.get("photo_id")
        action = request.json.get("action")
        user_id = request.json.get("user_id")
        # action是否合法(add, remove)
        if action not in ["add", "remove"]:
            return generate_response(status_code=10001, message="参数错误")
        # 是否存在这条评论
        try:
            photo = Photo.query.get(photo_id)
        except Exception as e:
            current_app.logger.error(e)
            return generate_response(status_code=10001, message="评论查询失败")
        if not photo:
            return generate_response(status_code=10001, message="不存在该评论")
        user = UserManager.query.get(user_id)
        if not user:
            return generate_response(status_code=10001, message="不存在该用户")
        # 根据action执行操作
        old_photo_like = Like.query.filter_by(photo_id=photo_id, user_id=user_id).first()
        if action == "add":
            if not old_photo_like:
                new_photo_like = Like()
                new_photo_like.comment_id = photo_id
                new_photo_like.user_id = user_id
                photo.like_count += 1
                print(photo.like_count)
                db.session.add(new_photo_like)
                return generate_response(message="点赞成功！")
        else:
            if old_photo_like:
                photo.like_count -= 1
                db.session.delete(old_photo_like)
                return generate_response(status_code=10001, message="取消点赞")

api.add_resource(LikeView, "/like")